package com.souku.finance.application.ui.invite;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.manager.RequestManager;
import com.jungly.gridpasswordview.GridPasswordView;
import com.souku.finance.application.R;
import com.souku.finance.application.base.BaseActivity;
import com.souku.finance.application.bean.AddpointBean;
import com.souku.finance.application.bean.PaySuccessBean;
import com.souku.finance.application.bean.PreBuyBean;
import com.souku.finance.application.bean.RedpacketBean;
import com.souku.finance.application.utils.Constant;
import com.souku.finance.application.http.UrlConstact;
import com.souku.finance.application.dialog.CheckPaypwdDialog;
import com.souku.finance.application.dialog.PayInfoDialog;
import com.souku.finance.application.ui.mine.MineFragment;
import com.souku.finance.application.utils.EdittextListenUtil;
import com.souku.finance.application.utils.JsonUtil;
import com.souku.finance.application.utils.MyTextUtil;
import com.souku.finance.application.utils.ParamUtil;
import com.souku.finance.application.utils.PayUtil;
import com.souku.finance.application.utils.ShareUtil;
import com.souku.finance.application.utils.TextWatch;
import com.souku.finance.application.utils.ToastUtil;
import com.souku.finance.application.widget.ButtonWait;
import com.souku.finance.application.widget.MyTextView;
import com.souku.finance.application.http.volley.ReqListener;
import com.souku.finance.application.http.volley.SuccessError;

import java.util.HashMap;

/**
 * Created by Android on 2016/12/19.
 */

public class PayActivity extends BaseActivity implements View.OnClickListener {

    protected RelativeLayout topBack;
    protected TextView topTitle;
    protected MyTextView tvRate;
    protected MyTextView tvInvestAmountRemain;
    protected TextView tvMoney;
    protected EditText etMoney;
    protected TextView tvRed;
    protected TextView tvAddpoint;
    protected ButtonWait btnPay;
    protected RelativeLayout relativeRed;
    private RedpacketBean.ListBean redBean;
    protected RelativeLayout relativeAddpoint;
    private AddpointBean.ListBean addPointBean;
    private Dialog payInfoDialog;
    private Dialog checkPaypwdDialog;
    private PreBuyBean bean;
    //标id
    private String deailId = "";
    //投资金额
    private double inviteMoney;
    //剩余
    private double inviteMax;
    //限投
    private double inviteDefine;
    //起投金额
    private double inviteMin;
    //余额
    private double money;
    //标的天数
    private int days;

    @Override
    public void internet() {
        getPreBuy();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.act_pay);
        deailId = getIntent().getStringExtra(Constant.Default);
        initView();
        topTitle.setText("购买");
        etMoney.addTextChangedListener(new TextWatch(new TextWatch.TextChanged() {
            @Override
            public void change(CharSequence s, int start, int before, int count) {
                //输入变化检测优惠
                if (!MyTextUtil.isEmpty(s.toString().trim())) {
                    inviteMoney = Double.parseDouble(s.toString().trim());
                    checkDiscount();
                }
            }
        }));
    }

    @Override
    protected void onResume() {
        super.onResume();
        getPreBuy();
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.top_back) {
            finish();
        } else if (view.getId() == R.id.relative_red) {
            if (checkMoney()) {
                Intent intent = new Intent(this, RedpacketActivity.class);
                intent.putExtra(Constant.Default, redBean);
                intent.putExtra(Constant.DefaultMore, inviteMoney);
                intent.putExtra(Constant.DefaultMost, days);
                startActivityForResult(intent, 0);
            }
        } else if (view.getId() == R.id.relative_addpoint) {
            if (checkMoney()) {
                Intent intent = new Intent(this, AddpointActivity.class);
                intent.putExtra(Constant.Default, addPointBean);
                intent.putExtra(Constant.DefaultMore, inviteMoney);
                intent.putExtra(Constant.DefaultMost, days);
                startActivityForResult(intent, 0);
            }
        } else if (view.getId() == R.id.btn_pay) {
            if (checkMoney()) {
                String money = etMoney.getText().toString().trim();
                if (!TextUtils.isEmpty(money)) {
                    getIsPay(PayUtil.getEoIntMoney(money));
                }
                btnPay.setEnabled(false);
            }
        }
    }

    private void initView() {
        topBack = (RelativeLayout) findViewById(R.id.top_back);
        topBack.setOnClickListener(PayActivity.this);
        topTitle = (TextView) findViewById(R.id.top_title);
        tvRate = (MyTextView) findViewById(R.id.tv_rate);
        tvInvestAmountRemain = (MyTextView) findViewById(R.id.tv_investAmountRemain);
        tvMoney = (TextView) findViewById(R.id.tv_money);
        etMoney = (EditText) findViewById(R.id.et_money);
        tvRed = (TextView) findViewById(R.id.tv_red);
        tvAddpoint = (TextView) findViewById(R.id.tv_addpoint);
        btnPay = (ButtonWait) findViewById(R.id.btn_pay);
        btnPay.setOnClickListener(PayActivity.this);
        relativeRed = (RelativeLayout) findViewById(R.id.relative_red);
        relativeRed.setOnClickListener(PayActivity.this);
        relativeAddpoint = (RelativeLayout) findViewById(R.id.relative_addpoint);
        relativeAddpoint.setOnClickListener(PayActivity.this);
    }

    //购买前信息
    private void getPreBuy() {
        HashMap<String, String> map = ParamUtil.getParams();
        map.put("itemId", deailId);
        RequestManager.getInstance().post(UrlConstact.PRE_BUY, ParamUtil.getSing(map), new ReqListener(this, new SuccessError() {
            @Override
            public void onSuccess(String response) {
                if (JsonUtil.getCode(response) == 1) {
                    bean = JsonUtil.fastBean(JsonUtil.getData(response).toString(), PreBuyBean.class);
                    setData();
                } else {
                    btnPay.setEnabled(true);
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }

            @Override
            public void onError(String errorMsg) {
                btnPay.setEnabled(true);
                ToastUtil.show("网络错误");
            }
        }), ParamUtil.getHeaders());
    }

    //生成订单
    private void getPrePay(int paymoney) {
        HashMap<String, String> map = ParamUtil.getParams();
        map.put("itemId", deailId);
        map.put("amount", paymoney + "");
        if (redBean != null) {
            map.put("ecv", redBean.getId());
        }
        if (addPointBean != null) {
            map.put("irc", addPointBean.getId());
        }
        RequestManager.getInstance().post(UrlConstact.PRE_PAY, ParamUtil.getSing(map), new ReqListener(this, new SuccessError() {
            @Override
            public void onSuccess(String response) {
                btnPay.setEnabled(true);
                if (JsonUtil.getCode(response) == 1) {
                    //计算弹出框数据逻辑
                    final String orderId = JsonUtil.getString(JsonUtil.getData(response), "orderId");
                    double balance;
                    double redmoney = 0;
                    double cardmoney;
                    if (redBean != null) {
                        redmoney = Double.parseDouble(MyTextUtil.setMoneyToElement(redBean.getMoney()));
                        if (money + redmoney < inviteMoney) {
                            cardmoney = inviteMoney - money - redmoney;
                            balance = money;
                        } else {
                            cardmoney = 0;
                            balance = inviteMoney - redmoney;
                        }
                    } else {
                        if (money < inviteMoney) {
                            cardmoney = inviteMoney - money;
                            balance = money;
                        } else {
                            cardmoney = 0;
                            balance = inviteMoney;
                        }
                    }
                    //弹出框
                    showPayInfoDialog(orderId, balance, redmoney, cardmoney);
                } else {
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }

            @Override
            public void onError(String errorMsg) {
                btnPay.setEnabled(true);
                ToastUtil.show("网络错误");
            }
        }), ParamUtil.getHeaders());
    }

    public void getIsPay(final int paymoney) {
        HashMap<String, String> map = ParamUtil.getParams();
        map.put("userId", ShareUtil.getInstance().getString(Constant.UserId));
        map.put("amount", paymoney + "");
        if (redBean == null) {
            map.put("couponId", "0");
        } else {
            map.put("couponId", redBean.getId() + "");
        }
        if (addPointBean == null) {
            map.put("incInterestCpId", "0");
        } else {
            map.put("incInterestCpId", addPointBean.getId() + "");
        }
        map.put("dealId", deailId);
        map.put("error_url", "");

//        RequestManager.getInstance().post("http://192.168.1.108:8080/invest/judgeAmtIsOver.do", map, new ReqListener(this, new SuccessError() {
//            @Override
//            public void onSuccess(String response) {
//                btnPay.setEnabled(true);
//                if (JsonUtil.getCode(response) == 0) {
//                    ToastUtil.show("OK");
//                } else {
//                    ToastUtil.show(JsonUtil.getMessage(response));
//                }
//            }
//
//            @Override
//            public void onError(String errorMsg) {
//                btnPay.setEnabled(true);
//                ToastUtil.show("网络错误");
//            }
//        }), ParamUtil.getHeaders());

        String str = "memberId=" + ShareUtil.getInstance().getString(Constant.UserId)
                + "&amount=" + paymoney + ""
                + "&id=" + deailId
                + "&accessToken=" + ShareUtil.getInstance().getString(Constant.Token)
                + "&appId=app";

        //id=1&memberId=53&amount=10000&accessToken=adsfafafadf&appId=app
//        String url = "id=1&memberId=53&amount=10000&accessToken=adsfafafadf&appId=app";

        RequestManager.getInstance().get(UrlConstact.PAY_IS + "?" + str, new ReqListener(this, new SuccessError() {

            @Override
            public void onSuccess(String response) {
                btnPay.setEnabled(true);
                if (JsonUtil.getErrorCode(response) == 0) {
                    Intent intent = new Intent(PayActivity.this, PayWebActivity.class);
                    intent.putExtra("deailId", deailId);
                    intent.putExtra("couponId", redBean == null ? "0" : redBean.getId());
                    intent.putExtra("incInterestCpId", addPointBean == null ? "0" : addPointBean.getId());
                    intent.putExtra("amount", paymoney + "");
                    startActivity(intent);
                } else {
                    //{"errorCode":9999,"errorMessage":"未开通E账户,不能投资"}
                    ToastUtil.show(JsonUtil.getErrorMessage(response));
                }
            }

            @Override
            public void onError(String errorMsg) {
                btnPay.setEnabled(true);
                ToastUtil.show("网络错误");
            }
        }), 0);

    }

    //弹出确定切面
    private void showPayInfoDialog(final String orderId, final double balance, double redmoney, double cardmoney) {
        payInfoDialog = new PayInfoDialog(PayActivity.this, inviteMoney + "", balance + "", redBean == null ? null : redmoney + "", cardmoney + "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                payInfoDialog.dismiss();
                showCheckPaypwdDialog(orderId, balance);
            }
        });
        payInfoDialog.show();
    }

    //弹出密码输入切面
    private void showCheckPaypwdDialog(final String orderId, double money) {
        checkPaypwdDialog = new CheckPaypwdDialog(PayActivity.this, "支付", money + "", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v.getId() == R.id.iv_closed) {
                    checkPaypwdDialog.dismiss();
                } else if (v.getId() == R.id.tv_resetpwd) {

                }
            }
        }, new GridPasswordView.OnPasswordChangedListener() {
            @Override
            public void onTextChanged(String psw) {

            }

            @Override
            public void onInputFinish(String psw) {
                btnPay.setEnabled(false);
                checkPaypwdDialog.dismiss();
                payOrder(orderId);
            }
        });
        checkPaypwdDialog.show();
    }

    //支付订单
    private void payOrder(String orderId) {
        HashMap<String, String> map = ParamUtil.getParams();
        map.put("orderId", orderId);
        RequestManager.getInstance().post(UrlConstact.PAY_ORDER, ParamUtil.getSing(map), new ReqListener(this, new SuccessError() {
            @Override
            public void onSuccess(String response) {
                if (JsonUtil.getCode(response) == 1) {
                    MineFragment.isChange = true;
                    btnPay.setEnabled(true);
                    //购买成功并且产品不是活期，置为新手。避免新手第二次购买
                    if (!deailId.equals("1")) {
                        ShareUtil.getInstance().putExtra(Constant.IsNewHand, false);
                    }
                    Intent intent = new Intent(PayActivity.this, PaySuccessActivity.class);
                    intent.putExtra(Constant.Default, new PaySuccessBean(bean.getDealInfo().getDealName(), inviteMoney + ""));
                    startActivity(intent);
                    finish();
                } else {
                    btnPay.setEnabled(true);
                    ToastUtil.show(JsonUtil.getMessage(response));
                }
            }

            @Override
            public void onError(String errorMsg) {
                btnPay.setEnabled(true);
                ToastUtil.show("网络错误");
            }
        }), ParamUtil.getHeaders());
    }

    private void setData() {
        int dealDate = Integer.parseInt(bean.getDealInfo().getDealDate());
        //天数
        days = bean.getDealInfo().getDealDateType().equals("0") ? dealDate : dealDate * 12;
        //利率
        tvRate.setText(MyTextUtil.doubleFormat(Double.parseDouble(bean.getDealInfo().getRate())));
        //剩余可投,元
        inviteMax = (Integer.parseInt(bean.getDealInfo().getBorrowAmount()) - Integer.parseInt(bean.getDealInfo().getInvestmentAmount())) * 0.01;
        //最低起投,元
        inviteMin = Integer.parseInt(bean.getDealInfo().getMinInvestment()) * 0.01;
        //投标上限,元
        inviteDefine = Integer.parseInt(bean.getDealInfo().getMaxInvestment()) * 0.01;
        tvInvestAmountRemain.setText(MyTextUtil.doubleFormat(inviteMax));
        //余额
        money = Integer.parseInt(bean.getMoney()) * 0.01;
        tvMoney.setText(MyTextUtil.doubleFormat(money));
        //限制输入两位小数，最大金额不能超过可投或限投,设置金额hint
        if (inviteDefine == 0) {
            if (inviteMin == 0) {
                etMoney.setHint("请输入金额");
            } else {
                etMoney.setHint(inviteMin + "起投");
            }
            EdittextListenUtil.setDouble(etMoney, inviteMax);
        } else {
            if (inviteMin == 0) {
                etMoney.setHint("限投" + inviteDefine);
            } else {
                etMoney.setHint(inviteMin + "起投，限投" + inviteDefine);
            }
            EdittextListenUtil.setDouble(etMoney, inviteDefine > inviteMax ? inviteMax : inviteDefine);
        }
        //红包相关
        if (redBean != null) {
            relativeRed.setVisibility(View.VISIBLE);
            tvRed.setText(MyTextUtil.setMoneyToElement(redBean.getMoney()));
        } else if (bean.getDealInfo().getUseEcv().equals("1")) {
            relativeRed.setVisibility(View.VISIBLE);
            if (!MyTextUtil.isEmpty(bean.getAvailableEcv())) {
                if (bean.getAvailableEcv().equals("0")) {
                    tvRed.setText("无可用红包");
                    relativeRed.setOnClickListener(null);
                } else {
                    tvRed.setText("请选择");
                    relativeRed.setOnClickListener(this);
                }
            }
        } else {
            relativeRed.setVisibility(View.INVISIBLE);
        }

        //加息券相关
        if (addPointBean != null) {
            relativeAddpoint.setVisibility(View.VISIBLE);
            tvAddpoint.setText(addPointBean.getRate() + "%");
        } else if (bean.getDealInfo().getUseRate().equals("1")) {
            relativeAddpoint.setVisibility(View.VISIBLE);
            if (bean.getAvailableIrc().equals("0")) {
                tvAddpoint.setText("无可用加息券");
                relativeAddpoint.setOnClickListener(null);
            } else {
                tvAddpoint.setText("请选择");
                relativeAddpoint.setOnClickListener(this);
            }
        } else {
            relativeAddpoint.setVisibility(View.INVISIBLE);
        }
    }

    //判断金额
    private boolean checkMoney() {
        String str = etMoney.getText().toString().trim();
        if (MyTextUtil.isEmpty(str)) {
            ToastUtil.show("请输入投标金额");
            return false;
        }
        inviteMoney = Double.parseDouble(str);
        if (inviteMoney == 0) {
            ToastUtil.show("请输入投标金额");
            return false;
        }
        //小于最低可投
        if (inviteMoney < inviteMin) {
            //剩余可投小于起投金额的情况
            if (inviteMax < inviteMin) {
                if (inviteMoney != inviteMax) {
                    ToastUtil.show("请输入固定金额" + inviteMax);
                    return false;
                }
            } else {
                ToastUtil.show("投标金额不能低于起投金额");
                return false;
            }
        }
        return true;
    }

    //判断优惠
    private void checkDiscount() {
        if (redBean != null) {
            int minThresholdRed = Integer.parseInt(redBean.getMinThreshold());
            if (minThresholdRed != 0) {
                if (inviteMoney * 100 < minThresholdRed) {
                    redBean = null;
                    tvRed.setText("请选择");
                }
            }
        }

        if (addPointBean != null) {
            int minThresholdAdd = Integer.parseInt(addPointBean.getMinThreshold());
            if (minThresholdAdd != 0) {
                if (inviteMoney * 100 < minThresholdAdd) {
                    addPointBean = null;
                    tvAddpoint.setText("请选择");
                }
            }
        }
    }

    //选择加息券和红包的返回处理
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null) return;
        if (resultCode == 0) {
            redBean = data.getParcelableExtra(Constant.Default);
        } else if (resultCode == 1) {
            addPointBean = data.getParcelableExtra(Constant.Default);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (payInfoDialog != null) {
            payInfoDialog.dismiss();
        }
        if (checkPaypwdDialog != null) {
            checkPaypwdDialog.dismiss();
        }
        if (!btnPay.isEnabled()) {
            btnPay.setEnabled(true);
        }
    }
}
